﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyNeighbourhood.Data;
using MyNeighbourhood.Models;
using System.IO;

namespace MyNeighbourhood.Managers
{
    public class EventsManager : BaseManager
    {
        private LocationsManager locationsManager = new LocationsManager();
        private ParticipantsManager participantsManager = new ParticipantsManager();

        public Event CreateOrUpdateEvent(EventModel model, HttpFileCollectionBase files)
        {
            try
            {
                Event eventDb;

                if (model.EventId != 0)
                {
                    eventDb = this.GetEventById(model.EventId);
                }
                else
                {
                    eventDb = new Event();
                }

                eventDb.AdditionalInfo = model.AdditionalInfo;
                eventDb.Email = model.Email;
                eventDb.IsPublic = model.IsPublic;
                eventDb.Name = model.Name;
                eventDb.Phone = model.Phone;
                eventDb.Presentation = model.Presentation;
                eventDb.Time = model.Time;
                eventDb.Type = (int)model.EventType;
                eventDb.Website = model.Website;
                eventDb.Date = new DateTime(model.Year, model.Month, model.Day);

                eventDb.OtherTargetTypes = model.OtherTargets;

                if (model.EventId != 0)
                {
                    this.DeleteExistingTargets(model.EventId);
                    this.DeleteExistingParticipants(model.EventId);
                }

                foreach (var type in model.Target)
                {
                    dbContext.EventTargets.Add(new EventTarget { Event = eventDb, TargetTypeId = type.TargetTypeId });
                }

                var location = locationsManager.CreateLocation(model.Location);
                if (location == null)
                {
                    throw new Exception();
                }
                eventDb.LocationId = location.LocationId;

                List<Participant> participants = new List<Participant>();
                foreach (var participantModel in model.Participants)
                {
                    var participant = participantsManager.CreateParticipant(model.EventId, participantModel);
                    participants.Add(participant);
                    if (participant != null)
                    {
                        dbContext.EventParticipants.Add(new EventParticipant { Event = eventDb, ParticipantId = participant.ParticipantId });
                    }
                }

                Event result = null;
                if (model.EventId == 0)
                {
                    result = dbContext.Events.Add(eventDb);
                }
                else
                {
                    result = eventDb;
                }

                dbContext.SaveChanges();

                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                          "Content\\Participants\\Photos");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFileBase hpf = files[i] as HttpPostedFileBase;

                    if (Path.GetFileName(hpf.FileName) == String.Empty)
                    {
                        continue;
                    }

                    string fileName = Path.Combine(path, i + "_" + result.EventId + "_" + Path.GetFileName(hpf.FileName));
                    hpf.SaveAs(fileName);
                    dbContext.Participants.Find(participants[i].ParticipantId).Photo = Path.Combine("\\Content\\Participants\\Photos", i + "_" + result.EventId + "_" + Path.GetFileName(hpf.FileName));
                }

                dbContext.SaveChanges();
                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void DeleteExistingParticipants(int eventId)
        {
            var participantsToDelete = dbContext.EventParticipants.Where(x => x.EventId == eventId);
            foreach (var participant in participantsToDelete)
            {
                dbContext.EventParticipants.Remove(participant);
            }
        }

        private void DeleteExistingTargets(int eventId)
        {
            var targetsToDelete = dbContext.EventTargets.Where(x => x.EventId == eventId);
            foreach (var target in targetsToDelete)
            {
                dbContext.EventTargets.Remove(target);
            }
        }

        public Event GetEventById(int id)
        {
            return dbContext.Events.Find(id);
        }

        internal bool IsTargetChecked(int targetId, int eventId)
        {
            return dbContext.EventTargets.FirstOrDefault(x => x.TargetTypeId == targetId && x.EventId == eventId) != null;
        }
    }
}